<?php

use ba\Filesystem;
use app\admin\library\module\Server;

if (!function_exists('get_account_verification_type')) {

    /**
     * 获取可用的账户验证方式
     * 用于：用户找回密码|用户注册
     * @return string[] email=电子邮件,mobile=手机短信验证
     * @throws Throwable
     */
    function get_account_verification_type(): array
    {
        $types = [];

        // 电子邮件，检查后台系统邮件配置是否全部填写
        $sysMailConfig = get_sys_config('', 'mail');
        $configured    = true;
        foreach ($sysMailConfig as $item) {
            if (!$item) {
                $configured = false;
            }
        }
        if ($configured) {
            $types[] = 'email';
        }

        // 手机号，检查是否安装短信模块
        $sms = Server::getIni(Filesystem::fsFit(root_path() . 'modules/sms/'));
        if ($sms && $sms['state'] == 1) {
            $types[] = 'mobile';
        }

        return $types;
    }
}

if (!function_exists('makeRequest')) {
    function makeRequest($url, $method = 'GET', $data = [], $headers = []) {
        $curl = curl_init();
        $defaultHeaders = [
            'User-Agent: WeChatAPI/1.0',
            'Accept: application/json',
            'Connection: keep-alive'
        ];

        if ($method === 'POST') {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
            $defaultHeaders[] = 'Content-Type: application/json';
        } elseif (!empty($data)) {
            $url .= '?' . http_build_query($data);
        }

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => array_merge($defaultHeaders, $headers),
        ]);

        $response = curl_exec($curl);
        $error = curl_error($curl);
        curl_close($curl);

        if ($error) {
            throw new Exception('CURL Error: ' . $error);
        }

        return json_decode($response, true);
    }
}
